const dayjs = require('dayjs');
/**
 * 基础Model类
 */
const cloud = require('../cloud/cloud.js');
const util = require('../helpers/util.js');

class Model {
    /**
     * 构造函数
     */
    constructor() {
        this._collection = null;
        this._db = null;
        this._where = {};
        this._createTime = util.time();
    }

    /**
     * 设置集合
     * @param {string} collection 集合名
     */
    setCollection(collection) {
        this._collection = collection;
    }

    /**
     * 获取当前时间戳
     */
    time() {
        return util.time();
    }

    /**
     * 获取当前日期时间
     */
    now() {
        return util.formatDate(dayjs(), 'YYYY-MM-DD HH:mm:ss');
    }

    /**
     * 获取集合
     */
    getCollection() {
        return this._collection;
    }

    /**
     * 获取数据库对象
     */
    getDB() {
        if (!this._db) {
            this._db = cloud.database();
        }
        return this._db;
    }

    /**
     * 构建查询条件
     * @param {object} where 查询条件
     */
    where(where = {}) {
        this._where = where;
        return this;
    }

    /**
     * 获取单条记录
     * @param {object} where 查询条件
     */
    async getOne(where = {}) {
        if (where && Object.keys(where).length > 0) {
            this._where = where;
        }
        
        try {
            const collection = this.getCollection();
            const query = this.getDB().collection(collection);
            
            if (Object.keys(this._where).length > 0) {
                return await query.where(this._where).limit(1).get().then(res => {
                    if (res.data && res.data.length > 0) {
                        return res.data[0];
                    } else {
                        return null;
                    }
                });
            } else {
                return await query.limit(1).get().then(res => {
                    if (res.data && res.data.length > 0) {
                        return res.data[0];
                    } else {
                        return null;
                    }
                });
            }
        } catch (error) {
            console.error('[Model.getOne] 错误:', error);
            return null;
        }
    }

    /**
     * 获取多条记录
     * @param {object} where 查询条件
     * @param {object} orderBy 排序条件
     * @param {number} limit 限制条数
     * @param {number} skip 跳过条数
     */
    async getAll(where = {}, orderBy = {}, limit = 10, skip = 0) {
        if (where && Object.keys(where).length > 0) {
            this._where = where;
        }
        
        try {
            const collection = this.getCollection();
            let query = this.getDB().collection(collection);
            
            if (Object.keys(this._where).length > 0) {
                query = query.where(this._where);
            }
            
            // 处理排序
            if (orderBy && Object.keys(orderBy).length > 0) {
                for (let key in orderBy) {
                    query = query.orderBy(key, orderBy[key] === 1 ? 'asc' : 'desc');
                }
            }
            
            // 处理分页
            if (skip > 0) {
                query = query.skip(skip);
            }
            
            if (limit > 0) {
                query = query.limit(limit);
            }
            
            return await query.get().then(res => {
                return res.data || [];
            });
        } catch (error) {
            console.error('[Model.getAll] 错误:', error);
            return [];
        }
    }

    /**
     * 获取记录总数
     * @param {object} where 查询条件
     */
    async count(where = {}) {
        if (where && Object.keys(where).length > 0) {
            this._where = where;
        }
        
        try {
            const collection = this.getCollection();
            let query = this.getDB().collection(collection);
            
            if (Object.keys(this._where).length > 0) {
                query = query.where(this._where);
            }
            
            return await query.count().then(res => {
                return res.total || 0;
            });
        } catch (error) {
            console.error('[Model.count] 错误:', error);
            return 0;
        }
    }
}

module.exports = Model; 